package com.yanghui.eletask4.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import com.yanghui.eletask4.*
import com.yanghui.eletask4.core.TCPServer
import com.yanghui.eletask4.view.HeartBeatGraph
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket

class MainActivity : Activity() {

    companion object {
        val messageChannel: Channel<TerminalData> = Channel(5)
    }

    lateinit var deviceTextView: TextView
    lateinit var stepNumTextView: TextView
    lateinit var distanceTextView: TextView
    lateinit var heartBeatTextView: TextView
    lateinit var temperatureTextView: TextView
    lateinit var heartBeatGraph: HeartBeatGraph
    lateinit var tcpConnectSocket: Socket
    lateinit var tcpInputStream: InputStream
    lateinit var tcpOutputStream: OutputStream
    var deviceName = "等待设备连接"

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        deviceTextView = findViewById(R.id.Main_DeviceTextView)
        stepNumTextView = findViewById(R.id.Main_StepNumTextView)
        distanceTextView = findViewById(R.id.Main_MoveDistanceTextView)
        heartBeatTextView = findViewById(R.id.Main_HeartBeatTextView)
        temperatureTextView = findViewById(R.id.Main_TemperatureTextView)
        heartBeatGraph = findViewById(R.id.Main_HeartBeatGraph)

        val tcpServer = TCPServer(11451)
        tcpServer.run()

        GlobalScope.launch(Dispatchers.IO) {
            val fileInput: FileInputStream = try {
                openFileInput("DeviceName")
            } catch (e: FileNotFoundException) {
                val output = openFileOutput("DeviceName", MODE_PRIVATE)
                output.write("等待设备连接".toByteArray())
                output.flush()
                output.close()
                openFileInput("DeviceName")
            }
            deviceName = fileInput.bufferedReader().readLine()
            deviceTextView.text = deviceName
            fileInput.close()
        }

        GlobalScope.launch(Dispatchers.Main) {
            while (true) {
                when (val message = messageChannel.receive()) {
                    is LoginData -> {
                        Toast.makeText(this@MainActivity, "设备已连接", Toast.LENGTH_SHORT).show()
                        deviceName = message.deviceName
                        deviceTextView.text = message.deviceName
                    }
                    is SportData -> {
                        if (deviceTextView.text.toString() != deviceName) {
                            deviceTextView.text = deviceName
                            Toast.makeText(this@MainActivity, "设备已连接", Toast.LENGTH_SHORT).show()
                        }
                        stepNumTextView.text = message.stepNum.toString()
                        distanceTextView.text = "${message.moveDistance}m"
                        heartBeatTextView.text = "${message.heartBeat}次/分"
                        temperatureTextView.text = "${message.temperature}℃"
                    }
                    is LogOutData -> {
                        deviceTextView.text = "等待设备连接"
                        stepNumTextView.text = "数据缺失"
                        distanceTextView.text = "数据缺失"
                        heartBeatTextView.text = "数据缺失"
                        temperatureTextView.text = "数据缺失"
                        heartBeatGraph.clearData()
                        Toast.makeText(this@MainActivity, "设备已断开", Toast.LENGTH_SHORT).show()
                    }
                    is HeartWaveData -> {
                        heartBeatGraph.addData(message.wave)
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val fileOutput = openFileOutput("DeviceName", MODE_PRIVATE)
        fileOutput.write(deviceName.toByteArray())
        fileOutput.flush()
        fileOutput.close()
    }
}